//
//  JYShopCartController.m
//  JYFarm
//
//  Created by 花花 on 2017/11/4.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYShopCartController.h"
#import "JYShopCell.h"
#import "JYShopCartViewModel.h"
#import "JYShopCartBottomView.h"
#import "JYShopCartTableViewProxy.h"
#import "JYCommitOrderController.h"
#import "JYShowView.h"
#import <MJRefresh/MJRefresh.h>
#import "JYShopCartBottomView.h"
#import "PurchaseCarAnimationTool.h"
@interface JYShopCartController ()<JYShopCartViewModelDelegate>
@property(nonatomic)JYShopCartTopView *shopcartTopView;  // 购物车顶部视图

@property(nonatomic)JYShopCartBottomView *shopcartBottomView;  // 购物车底部视图

@property (nonatomic) JYShopCartViewModel *viewModel;   // 负责购物车逻辑处理

@property (nonatomic)JYShopCartTableViewProxy *shopcartTableViewProxy; //tableView代理

@property (nonatomic)NSMutableArray *shopcartListArray; //购物车数据列表
@end

@implementation JYShopCartController
#pragma mark - Life Cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loadDataFromNetwork];
    [self setupSubview];
    [self setupConstranints];
    [self setupRefresh];
    
}
- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setupRefresh) name:kCountChangeNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kHomeCountChangeNotification object:nil];
}

#pragma mark - setupRefresh
- (void)setupRefresh{
    
    JYWeakSelf;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadDataFromNetwork];
    }];
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark - loadDataFromNetwork
- (void)loadDataFromNetwork{
    
    [self.tableView.mj_header endRefreshing];
    
    [self requsetDataList];
    
}
- (void)requsetDataList{
    
    JYWeakSelf;
    [HTTPRequest POST:kUserShoppingTrolleyListUrl parameter:@{@"userId":LH.userId} success:^(id resposeObject) {

        if (SUCCESS) {
            NSLog("购物车数据 %@",resposeObject);
            
            self.shopcartListArray = [JYShopModel mj_objectArrayWithKeyValuesArray:resposeObject[@"data"]];
            
            [self.viewModel requestShopcartProductList:self.shopcartListArray];
            
            dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            });
            
        }else if ([resposeObject[@"result"] integerValue] == 14){ //暂时没有商品

            [self.shopcartListArray removeAllObjects];
            
            [self.tableView reloadData];
            
        }else{
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
        self.currentPageStatus = PageStatusSucceed;
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:(kNoNetworkTips) time:2.0];
        self.currentPageStatus = PageStatusError;
        self.emptyViewTapBlock = ^{
            [weakSelf pullDownRefresh:1];
        };
    }];
}
- (void)pullDownRefresh:(int)page{

    [self requsetDataList];
}
- (void)GoodCarTotalCountFormNetwork{
    
    [HTTPRequest POST:kUserShoppingTrolleyGoodsTotalUrl parameter:@{@"userId":LH.userId} success:^(id resposeObject) {
        JYWeakSelf;
        if (SUCCESS) {
            int totalCount = [resposeObject[@"data"] intValue];
            
            NSLog(@"购物车数量: %d",totalCount);
            if (totalCount>0) {
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",totalCount];
            }else{
                
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = nil;
            }
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark - setupTableView
- (void)setupSubview{
    
    [self.view addSubview:self.shopcartTopView];
    
    [self setupTableView];
    [self.view addSubview:self.shopcartBottomView];
    
}
- (void)setupTableView{

    [self.tableView registerNib:[UINib nibWithNibName:@"JYShopCell" bundle:nil] forCellReuseIdentifier:@"JYShopCellID"];
    self.tableView .showsVerticalScrollIndicator = NO;
    self.tableView .delegate = self.shopcartTableViewProxy;
    self.tableView .dataSource = self.shopcartTableViewProxy;
    
    self.tableView .sectionFooterHeight = 10;
    self.tableView .tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    self.tableView .tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    
}
#pragma mark - <JYShopCartViewModelDelegate>
//获取数据
- (void)shopcartRequestDataSuccessWithArray:(NSMutableArray *)dataArray{
    
    self.shopcartTableViewProxy.dataArray = dataArray;
    
    [self.tableView reloadData];
}
//总价格+押金价格+全部数量(没有用上)+(是否全选)
- (void)shopcartAccountForTotalPrice:(double)totalPrice DepositPrice:(double)depositPrice totalCount:(NSInteger)totalCount isAllSelected:(BOOL)isAllSelected{

    [self.shopcartBottomView configureShopcartBottomViewWithTotalPrice:totalPrice DepositPrice:depositPrice totalCount:totalPrice isAllselected:isAllSelected];
 
   [self.tableView reloadData];
}
//清空
- (void)shopcartClearDeleteAllProducts{
    
    [self.tableView reloadData];
}
//批量删除
- (void)shopcartWillDeleteSelectedProducts:(NSArray *)selectedProducts{
    
    if (selectedProducts.count>0) {
        
        JYWeakSelf;
        JYShowView *showView = [[JYShowView alloc]initWithFrame:CGRectMake(0, 0, showView_Width, showView_Height) isSected:YES alertMessage:@"删除后商品将不在显示，确认删除类商品吗?" btnHandler:^(JYShowType type) {
            
            if (type == JYShowTypeDone) {
                
                [self.viewModel deleteSelectedProducts:selectedProducts];
                
                [weakSelf GoodCarTotalCountFormNetwork];
                
                [self.tableView reloadData];
            }
        }];
        [showView show];
    }
}
//提交订单
- (void)shopcartCommitOrderForSelectedProducts:(NSArray *)selectedProducts{
    
    JYWeakSelf;
    NSLog(@"-------%@",selectedProducts);
    if (selectedProducts.count == 0) {
        
        UIView *bgView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        bgView.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.5];
        
        [[UIApplication sharedApplication].keyWindow addSubview:bgView];
        JYNoGoodsShowView*showView =  [[JYNoGoodsShowView alloc]initWithFrame:CGRectMake((Screen_Width - showView_Width)/2, (Screen_Height- showView_Height)/2, showView_Width, showView_Height)];
        [bgView addSubview:showView];
        
        [showView showText:@"您未选择任何商品，请选择商品后进行购买" onClickHandler:^{
            [bgView removeFromSuperview];
            [showView removeFromSuperview];
        }];
    }else if (selectedProducts.count>0){
        
        [weakSelf.navigationController pushViewController:[JYCommitOrderController new] animated:YES];
    }
}
#pragma mark - Setter && Getter Methods
- (JYShopCartTopView *)shopcartTopView {
    if (_shopcartTopView == nil){
        _shopcartTopView = [[JYShopCartTopView alloc] init];
        JYWeakSelf;
        _shopcartTopView.HandlerDeleteBtnOnClick=^(){ //删除
            [weakSelf.viewModel beginToDeleteSelectedProducts];
            [weakSelf GoodCarTotalCountFormNetwork];
            
        };
        _shopcartTopView.HandlerEmptyBtnOnClick =^(){ //清空

            JYShowView *showView = [[JYShowView alloc]initWithFrame:CGRectMake(0, 0, showView_Width, showView_Height) isSected:YES alertMessage:@"删除后商品将不在显示，确认删除类商品吗?" btnHandler:^(JYShowType type) {
                
                if (type == JYShowTypeDone) {
                    [weakSelf.viewModel deleteAllProducts];
                    [weakSelf GoodCarTotalCountFormNetwork];
                }
            }];
            [showView show];
        };
    }
    return _shopcartTopView;
}

- (JYShopCartViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel =[[JYShopCartViewModel alloc]init];
        _viewModel.delegate = self;
    }
    return _viewModel;
    
}
- (JYShopCartTableViewProxy *)shopcartTableViewProxy {
    if (_shopcartTableViewProxy == nil){
        JYWeakSelf;
        _shopcartTableViewProxy = [[JYShopCartTableViewProxy alloc] init];
        _shopcartTableViewProxy.ShopCartHandlerSelectBlock = ^(BOOL isSelected,NSIndexPath *indexPath){ //选中
            
            [weakSelf.viewModel selectProductAtIndexPath:indexPath isSelected:isSelected];
        };
        _shopcartTableViewProxy.ShopCartHandlerDeleteBlock = ^(NSIndexPath *indexPath){ //左滑删除
            
            JYShowView *showView = [[JYShowView alloc]initWithFrame:CGRectMake(0, 0, showView_Width, showView_Height) isSected:YES alertMessage:@"删除后商品将不在显示，确认删除类商品吗?" btnHandler:^(JYShowType type) {
                if (type == JYShowTypeDone) {
                    
                    [weakSelf.viewModel deleteProductTableView:weakSelf.tableView AtIndexPath:indexPath];
                    [weakSelf GoodCarTotalCountFormNetwork];
                    
                }
            }];
            [showView show];
        };
        _shopcartTableViewProxy.ShopCartHandlerChangeCountBlock = ^(NSInteger count, NSIndexPath *indexPath){ //数量的变化
            
            [weakSelf.viewModel changeCountAtIndexPath:indexPath count:count];
        };
        
        _shopcartTableViewProxy.joinShopCarAninationBlock = ^(UIImageView *imageView, NSIndexPath *indexPath){
            
            CGRect rect = [weakSelf.tableView rectForRowAtIndexPath:indexPath];
            rect.origin.y = rect.origin.y - [weakSelf.tableView contentOffset].y;
            CGRect imageViewRect = imageView.frame;
            imageViewRect.origin.y = rect.origin.y+imageViewRect.origin.y;
            [[PurchaseCarAnimationTool shareTool]startAnimationandView:imageView andRect:imageViewRect andFinisnRect:CGPointMake(ScreenWidth/4 *2.5, ScreenHeight-49) andFinishBlock:^(BOOL finish) {
                UIView *tabbarBtn = weakSelf.tabBarController.tabBar.subviews[3];
                [PurchaseCarAnimationTool shakeAnimation:tabbarBtn];
                
                [weakSelf GoodCarTotalCountFormNetwork];
            }];
        };
        
    }
    return _shopcartTableViewProxy;
}
- (JYShopCartBottomView *)shopcartBottomView {
    if (_shopcartBottomView == nil){
        _shopcartBottomView = [[JYShopCartBottomView alloc] init];
        JYWeakSelf;
        _shopcartBottomView.HandlerAllBtnOnClick = ^(BOOL isSelected){ //全选
            
            [weakSelf.viewModel selectAllProductWithStatus:isSelected];
        };
        _shopcartBottomView.HandlerCommitOrderBtnOnClick = ^(){ //提交订单
            
            [weakSelf.viewModel commitOdrerSelectedProducts];
        };
    }
    return _shopcartBottomView;
}
- (NSMutableArray *)shopcartListArray{
    
    if (!_shopcartListArray) {
        _shopcartListArray = [NSMutableArray array];
    }
    return _shopcartListArray;
}
#pragma mark - setupConstranints
- (void)setupConstranints{
    
    JYWeakSelf;
    [_shopcartTopView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(weakSelf.view);
        make.height.equalTo(@50);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@50);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.shopcartBottomView.mas_top);
    }];
    [self.shopcartBottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(weakSelf.view);
        make.height.equalTo(@50);
    }];
}
#pragma mark - dealloc
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end

